package dao;

import models.UserInfo;
import utils.DBUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IDEA
 * author:ju bai
 * Date:2021/4/7
 * Time:20:58
 **/
public class UserInfoDao {

    /**
     * 用户注册：（往数据库中添加用户密码）
     * @param username
     * @param password
     * @return
     * @throws SQLException
     */
    public int add(String username, String password) throws SQLException {
        int result = 0;
        Connection connection = DBUtils.getConnection();
        String sql = "insert into userinfo(username,password) values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,username);
        statement.setString(2,password);
        result=statement.executeUpdate();
        DBUtils.close(connection,statement,null);
        return result;
    }

    /**
     * 用户查询：（查询数据库中的用户密码是否正确）
     * @param username
     * @param password
     * @return
     * @throws SQLException
     */
    public UserInfo find(String username, String password) throws SQLException {
        UserInfo userInfo = new UserInfo();
        Connection connection = DBUtils.getConnection();
        String sql = "select * from userinfo where username =? and password =?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1,username);
        statement.setString(2,password);
        //查询数据库
        ResultSet resultSet = statement.executeQuery();
        while(resultSet.next()){
            userInfo.setId(resultSet.getInt("id"));
            userInfo.getUsername(resultSet.getString("username"));
            userInfo.getPassword(resultSet.getString("password"));
        }
        //关闭数据库链接
        DBUtils.close(connection,statement,resultSet);
        return userInfo;
    }
}
